package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {

        //站在我的角度，保存一份好友数据
        //站在好友的角度，也要保存一份数据
        //1.判断好友关系数据库中是否已经存在
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query = Query.query(criteria);
        boolean result = mongoTemplate.exists(query, Friend.class);

        if(!result){

            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        Criteria criteria1 = Criteria.where("friendId").is(userId).and("userId").is(friendId);
        Query query1 = Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1){
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }

    }

    /**
     * 分页查询好友
     * @param currentId
     * @param page
     * @param pageSize
     * @return
     */
    public List<Friend> queryFriends(Long currentId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(currentId);
        Query query = Query.query(criteria);
        query.skip((page - 1 ) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));

        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;

    }
}
